package com.seckill.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author levi
 * @version 1.0
 * @datetime 2021/9/6 21:50
 * @decription 消息发送（生产者）
 **/
@Service
@Slf4j
public class MQSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 点对点模式
     *
     * @param msg
     */
    public void send(Object msg) {
        log.info("发送消息：{}", msg);
        rabbitTemplate.convertAndSend("queue", msg);
    }

    /**
     * fanout模式 广播
     *
     * @param msg
     */
    public void send2FanoutExchange(Object msg) {
        log.info("发送fanout消息：{}", msg);
        rabbitTemplate.convertAndSend("fanoutExchange", "", msg);
    }

    /**
     * direct路由键模式
     *
     * @param msg
     */
    public void send2DirectExchange01(Object msg) {
        log.info("发送red消息：{}", msg);
        rabbitTemplate.convertAndSend("directExchange", "queue.red", msg);
    }

    public void send2DirectExchange02(Object msg) {
        log.info("发送green消息：{}", msg);
        rabbitTemplate.convertAndSend("directExchange", "queue.green", msg);
    }

    /**
     * topic主题模式
     */
    public void send2TopicExchange01(Object msg) {
        log.info("发送#.#消息：{}", msg);
        rabbitTemplate.convertAndSend("topicExchange", "queue.red.message", msg);
    }

    public void send2TopicExchange02(Object msg) {
        log.info("发送*.#消息：{}", msg);
        rabbitTemplate.convertAndSend("topicExchange", "message.queue.green.abc", msg);
    }

    /**
     * headers头消息模式
     */
    public void send2HeadersExchange01(String msg) {
        log.info("发送headers all消息：{}", msg);
        MessageProperties properties = new MessageProperties();
        properties.setHeader("color", "red");
        properties.setHeader("speed", "fast");
        Message message = new Message(msg.getBytes(), properties);
        rabbitTemplate.convertAndSend("headerExchange", "", message);
    }

    public void send2HeadersExchange02(String msg) {
        log.info("发送headers any消息：{}", msg);
        MessageProperties properties = new MessageProperties();
        properties.setHeader("color", "red");
        properties.setHeader("speed", "normal");
        Message message = new Message(msg.getBytes(), properties);
        rabbitTemplate.convertAndSend("headerExchange", "", message);
    }

}
